﻿using Mengsk.ProxyDelivery.HTTPHelpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace Mengsk.ProxyDelivery.TaobaoAddressExport
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DataContractJsonSerializer sizeSer = new DataContractJsonSerializer(typeof(AreaResponse));

        private const string TITLE_CONTRY = "Country";
        private const string TITLE_STATE = "State";
        private const string TITLE_CITY = "City";
        private const string TITLE_REGION = "Region";
        private const string TITLE_TOWN = "Town";

        public MainWindow()
        {
            InitializeComponent();
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private string NextTitle(string current)
        {
            if (current == TITLE_CONTRY)
            {
                return TITLE_STATE;
            }

            if (current == TITLE_STATE)
            {
                return TITLE_CITY;
            }

            if (current == TITLE_CITY)
            {
                return TITLE_REGION;
            }

            if (current == TITLE_REGION)
            {
                return TITLE_TOWN;
            }

            throw new Exception("没有下级:" + current);
        }

        private XElement convertToXElement(Area area, string title)
        {
            XElement xe = new XElement(title);
            xe.Add(new XAttribute("Name", area.value), new XAttribute("Code", area.id));

            if (area.children != null && area.children.Count > 0)
            {
                foreach (var sub in area.children)
                {
                    if (sub.value.Contains("其它"))
                    {
                        Debug.WriteLine("已经忽略:" + sub);
                        continue;
                    }
                    try
                    {
                        xe.Add(convertToXElement(sub, NextTitle(title)));

                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(sub);
                        throw ex;
                    }
                }
            }
            return xe;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            String url = this.tbAddress.Text.Trim();
            if (String.IsNullOrWhiteSpace(url))
            {
                MessageBox.Show("地址不能为空");
                return;
            }

            try
            {

                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.DefaultExt = "xml";
                sfd.AddExtension = true;
                sfd.Filter = "*.xml|xml";

                bool? ret = sfd.ShowDialog();

                if (ret == null || ret.Value == false)
                {
                    return;
                }

                Dictionary<string, string> para = new Dictionary<string, string>();
                String content2 = MSHttpRestful.DoWithRetry(() => MSHttpRestful.PostUrlEncodeBodyReturnString(url, para, Encoding.GetEncoding("gb2312")), 5);
                content2 = content2.Substring(1, content2.Length - 3);
                Byte[] content = Encoding.UTF8.GetBytes(content2);
                using (MemoryStream ms = new MemoryStream(content))
                {
                    AreaResponse ar = this.sizeSer.ReadObject(ms) as AreaResponse;

                    if (ar.success == false)
                    {
                        MessageBox.Show("获取数据失败");
                        return;
                    }

                    XDocument xDoc = new XDocument();
                    xDoc.Add(new XElement("Address"));
                    XElement root = xDoc.Root;
                    foreach (var area in ar.nodes)
                    {
                        root.Add(this.convertToXElement(area, TITLE_CONTRY));
                    }
                    xDoc.Save(sfd.FileName);
                }
                MessageBox.Show(sfd.FileName, "已成功保存");
                //var obj = JsonConvert.DeserializeObject(content2, typeof(AreaResponse)) as AreaResponse;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}
